﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace NoteHelper.Model
{
    public static class DataAnnotationHelper
    {
        public static List<ValidationResult> GetValidationResults(object model)
        {
            var results = new List<ValidationResult>();
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            var context = new ValidationContext(model);
            Validator.TryValidateObject(model, context, results, true);

            return results;
        }

        public static string GetDisplayName(this Type objType, string propertyName)
        {
            string displayName = propertyName;
            var properties = TypeDescriptor.GetProperties(objType);
            // 此方法虽然简单，但是若propertyName不存在时会出异常
            // return properties[propertyName].DisplayName;
            foreach (PropertyDescriptor pro in properties)
            {
                if (pro.Name == propertyName)
                {
                    displayName = pro.DisplayName;
                    break;
                }
            }

            return displayName;
        }
    }
}
